local zhuoda = fk.CreateSkill {
  name = "wk_heg__zhuoda",
  tags = {Skill.Compulsory},
}

Fk:loadTranslationTable{
  ["wk_heg__zhuoda"] = "擢达",
  [":wk_heg__zhuoda"] = "锁定技，当你于出牌阶段使用首张锦囊牌结算后，你与此牌所有其他目标角色同时拼点，若你赢次数大于没赢，你<a href=':ElectedChange'>推举</a>且以此法选用的角色复原武将牌。",
}

local HG = require "packages/new_heg_diy_my/util"

zhuoda:addEffect(fk.CardUseFinished, {
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(zhuoda.name) and player.phase == Player.Play and player == target 
      and data.card and data.card.type == Card.TypeTrick and data.tos) then return false end
    local events = target.room.logic:getEventsOfScope(GameEvent.UseCard, 99, function(e)
      local use = e.data
      return use.from == player and use.card.type == Card.TypeTrick
    end, Player.HistoryPhase)
    return #events == 1
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if data.tos then
      local targets = {}
      for _, p in ipairs(data.tos) do
        if p ~= player and player:canPindian(p) then
          table.insert(targets, p)
        end
      end
      if #targets > 0 then
        local pindian = player:pindian(targets, zhuoda.name)
        local win, lose = 0, 0
        for _, p in ipairs(targets) do
          if pindian.results[p].winner then
            if pindian.results[p].winner == player then
              win = win + 1
            else
              lose = lose + 1
            end
          end
        end
        if win > lose then
          -- HG.DoElectedChange(room, player, zhuoda.name)
          local p_table = HG.DoElectedChange(room, player, zhuoda.name)
          if p_table then
            local p_player = p_table[1]
            if p_player then
              p_player:reset()
              -- room:handleAddLoseSkills(p_player, "wk_heg__jinti_zhuoda", nil)
              -- room:setPlayerMark(player, "_wk_heg__zhuoda_have", 1)
            end
          end
        end
      end
    end
  end,
})

-- local zhuoda_spec = {
--   can_refresh = function(self, event, target, player, data)
--     return player == target and player:getMark("_wk_heg__zhuoda_have") ~= 0
--   end,
--   on_refresh = function(self, event, target, player, data)
--     local room = player.room
--     for _, p in ipairs(room.alive_players) do
--       if p:hasSkill("wk_heg__jinti_zhuoda") then
--         room:handleAddLoseSkills(p, "-wk_heg__jinti_zhuoda", nil)
--         room:addPlayerMark(player, "@wk_heg__jinti_zhuoda", 1)
--       end
--     end
--     room:setPlayerMark(player, "_wk_heg__zhuoda_have", 0)
--   end,
-- }

-- zhuoda:addEffect(fk.TurnStart, zhuoda_spec)
-- zhuoda:addEffect(fk.BuryVictim, zhuoda_spec)

return zhuoda